package com.group2.view;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import java.awt.*;
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Objects;

import model.*;
import static model.netBase.IP;
public class ShoppingCar extends JFrame {

    private String currentName;
    private ArrayList<Goods> myGoods;

    public ShoppingCar(String sId, ArrayList<Goods> shopCar) {
        currentName = sId;
        myGoods = shopCar;
        init();
    }

    public void refreshMoney(JLabel money){
        try{
            Socket socket=new Socket(IP(),2000);
            socket.setSoTimeout(3000);
            //构建IO
            OutputStream os = socket.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
            bw.write("61" + '\n'+currentName+'\n');
            bw.flush();
            InputStream is = socket.getInputStream();
            ObjectInputStream ois = new ObjectInputStream(is);
            Object obj=ois.readObject();
            Account account=(Account) obj;
            money.setText(account.getAccountBalance()+"");
        }catch (Exception e){
            System.out.println("连接异常");
        }
    }
    public void init() {
        Font f = new Font("黑体", Font.PLAIN, 15);
        Font d = new Font("黑体", Font.BOLD, 17);
        Font g = new Font("黑体", Font.BOLD, 15);
        this.setTitle("我的购物车");
        this.setSize(530, 600);
        this.setResizable(false);
        //jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //ImageIcon icon = new ImageIcon("/images/add.png");
        // 创建内容面板，使用边界布局
        JPanel panel = new JPanel();
        JPanel panel2 = new JPanel(null);
        JPanel panel0 = new JPanel(null);
        JLabel intro = new JLabel("当前购物车内全部商品信息如下：");

        JLabel monshow = new JLabel("一卡通余额：");
        JLabel money = new JLabel();
        refreshMoney(money);

        intro.setFont(d);
        JButton Buy = new JButton();
        Buy.setFocusPainted(false);
        Buy.setIcon(new ImageIcon(UserLogOnFrame.class.getResource("/images/购买.png")));
        JButton Del = new JButton();
        Del.setFocusPainted(false);
        Del.setIcon(new ImageIcon(UserLogOnFrame.class.getResource("/images/delete.png")));

        panel0.setBounds(0, 0, 450, 100);
        intro.setBounds(50, 10, 300, 30);
        Buy.setBounds(385, 50, 30, 30);
        Del.setBounds(420, 50, 30, 30);
        panel.setBounds(40, 100, 450, 300);
        money.setBounds(150, 410, 120, 40);
        money.setFont(g);
        monshow.setFont(g);
        monshow.setBounds(50, 410, 120, 40);

        panel2.setBounds(0, 400, 550, 200);

        JTable table = new JTable();
        // 表头（列名）
        Object[] columnNames = {"编号", "品名", "种类", "价格", "剩余量", "选购数"};
        Object[][] rowData=new Object[myGoods.size()][6];

        for(int x=0;x<myGoods.size();x++){
            rowData[x][0]=myGoods.get(x).getId();
            rowData[x][1]=myGoods.get(x).getGoodsname();
            rowData[x][2]=myGoods.get(x).getGoodsstyle();
            rowData[x][3]=myGoods.get(x).getPrice();
            rowData[x][4]=myGoods.get(x).getSurplus();
            rowData[x][5]="1";
        }

        // 创建 表格模型
        DefaultTableModel tableModel = new DefaultTableModel(rowData, columnNames) {
            public boolean isCellEditable(int row,int column) {
                return false;
            }
        };

        table.setModel(tableModel);

        // 设置表格内容颜色
        table.setForeground(Color.BLACK);                   // 字体颜色
        table.setFont(new Font(null, Font.PLAIN, 14));      // 字体样式
        table.setSelectionForeground(Color.DARK_GRAY);      // 选中后字体颜色
        table.setSelectionBackground(Color.orange);     // 选中后字体背景
        table.setGridColor(Color.GRAY);                     // 网格颜色

        // 设置表头
        table.getTableHeader().setFont(f);  // 设置表头名称字体样式
        table.getTableHeader().setForeground(Color.blue);                // 设置表头名称字体颜色
        table.getTableHeader().setResizingAllowed(false);               // 设置不允许手动改变列宽
        table.getTableHeader().setReorderingAllowed(false);             // 设置不允许拖动重新排序各列

        // 设置行高
        table.setRowHeight(30);

        // 第一列列宽设置为40
        table.getColumnModel().getColumn(0).setPreferredWidth(40);

        // 设置滚动面板视口大小（超过该大小的行数据，需要拖动滚动条才能看到）
        table.setPreferredScrollableViewportSize(new Dimension(400, 280));

        // 把 表格 放到 滚动面板 中（表头将自动添加到滚动面板顶部）
        JScrollPane scrollPane = new JScrollPane(table);
        //table.getColumnModel().getColumn(5).setCellRenderer(new buttonadd("移除"));
        // 添加 滚动面板 到 内容面板
        panel.add(scrollPane);

        panel0.add(intro);
        panel0.add(Buy);
        panel0.add(Del);

        panel2.add(monshow);
        panel2.add(money);

        // 设置 内容面板 到 窗口
        this.getContentPane().add(panel0);
        this.getContentPane().add(panel);
        this.getContentPane().add(panel2);


        //设置筛选条
        RowSorter<TableModel> rowSorter = new TableRowSorter<TableModel>(tableModel);
        table.setRowSorter(rowSorter);

        Buy.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int num=myGoods.size();
                String[] result=new String[num];
                try {
                    Socket socket = new Socket(IP(), 2000);
                    socket.setSoTimeout(6000);
                    //构建IO
                    OutputStream os = socket.getOutputStream();
                    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
                    bw.write("53" + '\n'+
                            currentName+'\n'+
                            num +'\n');
                    for(int x=0;x<num;x++){
                        bw.write(myGoods.get(x).getId()+'\n');
                    }
                    bw.flush();
                    InputStream is=socket.getInputStream();
                    BufferedReader br=new BufferedReader(new InputStreamReader(is));
                    for(int x=0;x<num;x++){
                        result[x]=br.readLine();
                    }
                    socket.close();
                }catch (UnknownHostException a) {
                    throw new RuntimeException(a);
                } catch (IOException a) {
                    throw new RuntimeException(a);
                }
                //反馈购买情况
                for(int x=0;x<num;x++){
                    if(Objects.equals(result[x], "true")){
                        JOptionPane.showMessageDialog(null,myGoods.get(x).getGoodsname()+"购买成功！");
                    }
                    else{
                        JOptionPane.showMessageDialog(null, myGoods.get(x).getGoodsname()+"剩余量不足！");
                    }
                }
                myGoods.clear();
                refreshMoney(money);
            }
        });
        Del.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int count=table.getSelectedRow();
                myGoods.remove(count);
                Object rowData1[][]=new Object[50][6];
                for(int x=0;x<myGoods.size();x++){
                    rowData1[x][0]=myGoods.get(x).getId();
                    rowData1[x][1]=myGoods.get(x).getGoodsname();
                    rowData1[x][2]=myGoods.get(x).getGoodsstyle();
                    rowData1[x][3]=myGoods.get(x).getPrice();
                    rowData1[x][4]=myGoods.get(x).getSurplus();
                    rowData1[x][5]="1";
                }
                DefaultTableModel tableModel1 = new DefaultTableModel(rowData1, columnNames) {
                    public boolean isCellEditable(int row,int column) {
                        return false;
                    }
                };
                table.setModel(tableModel1);
                JOptionPane.showMessageDialog(null, "删除成功！");
            }
        });
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }
}